<?php
namespace app\store\controller\shop;

use app\store\controller\Controller;
use app\common\model\GetTui as GetTuiModel;
/**
 * 补油申请
 * Class Index
 * @package app\store\controller
 */
class Replenishment extends Controller
{
    public function index()
    {
		$where = [];
		$shop_id = $this->request->param("shop_id/d",0);
		if( $shop_id > 0 ) {
			$where['er.shop_id'] = $shop_id;
		}
		$newwhere = '';
		$merch = $this->request->param("merch" , '');
		if( $merch ) {
			$newwhere = 's.shop_id = "'.$merch.'" OR s.shop_name = "'.$merch.'"';
		}
		$status = $this->request->param('status/d' , -1);
		if( $status >= 0 ) {
			$where['er.status'] = $status;
		}
        $list = db("engineoil_replenishment")->where($where)->alias("er")->where($newwhere)->join("engineoil e" , 'e.id = er.eid')->join("yoshop_shop s",'s.shop_id = er.shop_id')->field("er.*,e.thumb,e.title,s.shop_name")->order("er.status ASC,er.id DESC")->paginate(15, false, ['query' => $this->request->request()])->each(function($item , $key){
			$fields = array('未审核' , '未通过' , '已通过' , '已发货' , '已收货' , '完成');
            $item['status_name'] = $fields[$item['status']];
            return $item;
        });
        $express_list = config("express_name_list");
		if( request()->isAjax() ) {
			exit(json_encode($list));
		}
        return $this->fetch('index', compact('list' , 'express_list'));
    }
    
    /**
     * 审核
     */
    public function inspect() {
        $id = $this->request->param("id/d" , 0);
        if( $id <= 0 ) $this->error('信息传递错误');
        $info = db("engineoil_replenishment")->where(['id' => $id])->find();
        if( !$info ) $this->error("审核数据不存在");
        $note = $this->request->param("note");
        $status = $this->request->param("status/d",1);
        $data =  db("engineoil")->where(['id' => $info['eid']])->find();
        if( !$data ) $this->error("机油数据不存在");
        if( $status == 2 ) {
            if( $data['stock'] < $info['stock'] ) {
                $this->error("仓库机油库存小于申请库存，请核对仓库机油库存");
            }
            $shop_info = db("shop")->where(['shop_id' => $info['shop_id']])->find();
            db("engineoil")->where(['id' => $info['eid']])->update(['stock' => $data['stock'] - $info['stock']]);
            db("engineoil_stock_log")->insert([
                'eid' => $info['eid'],
                'type' => 3,
                'content' => '分配机油：'.$info['stock'].'件到4s店【'.$shop_info['shop_name'].'】',
                'stock' => $info['stock'],
                'shop_id' => $info['shop_id'],
                'create_time' => time()
            ]);
			$obj = new  GetTuiModel;
			$obj->sendToClient($shop_info['user_id'] , '补油申请审核通知' , '您申请的补油'.($status == 2 ?'已通过审核，平台将尽快为您发货' : '审核失败').($note?',备注：' . $note:'').',详情请在商户中心查看');
        }
        db("engineoil_replenishment")->where(['id' => $id])->update(['status' => $status , 'note' => $note]);
        $this->success($status == 1 ? '操作成功' : '审核成功，请尽快发货');
    }
    
    /**
     * 发货
     */
    public function sendexpress() {
        $id = $this->request->param("id/d" , 0);
        if( $id <= 0 ) $this->error('信息传递错误');
        $info = db("engineoil_replenishment")->where(['id' => $id])->find();
        if( !$info ) $this->error("审核数据不存在");
        $express_name = $this->request->param("express_name");
        $express_no = $this->request->param("express_no");
        if( $express_name == '' || $express_no == '') {
            $this->error('信息传递错误');
        }
        $res = db('engineoil_replenishment')->where(['id' => $id])->update(['is_deliver' => 1 , 'express_name' => $express_name , 'express_no' => $express_no , 'status' => 3]);
        if( $res ) {
			$obj = new  GetTuiModel;
			$shop_info = db("shop")->where(['shop_id' => $info['shop_id']])->find();
			$obj->sendToClient($shop_info['user_id'] , '补油申请发货通知' , '您申请的补油产品现已发货，快递号【'.$express_no.'】,详情请在商户中心查看');
            $this->success('发货成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    /**
     * 快递信息
     */
    public function expressinfolist() {
        $id = $this->request->param("id/d" , 0);
        if( $id <= 0 ) $this->error('信息传递错误');
        $info = db("engineoil_replenishment")->where(['id' => $id])->find();
        if( !$info ) $this->error("数据不存在");
		
		
		$data = getExpress($info['express_no']);
        $info['express_name'] = config("express_name_list")[$info['express_name']];
        return json( ['data' => $info , 'code' => 1 , 'lists' => $data] );
    }
	
    public function datadelete() {
        $id = $this->request->post('id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('engineoil_replenishment')->where(['id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    public function delete() {
        $id = $this->request->post('id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('engineoil_stock_log')->where(['id' => $id])->update(['is_delete' => 0]);
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
	
	 public function export()
    {
		$where = [];
		$shop_id = $this->request->param("shop_id/d",0);
		if( $shop_id > 0 ) {
			$where['er.shop_id'] = $shop_id;
		}
		$status = $this->request->param('status/d' , -1);
		if( $status >= 0 ) {
			$where['er.status'] = $status;
		}
		
		$newwhere = '';
		$merch = $this->request->param("merch" , '');
		if( $merch ) {
			$newwhere = 's.shop_id = "'.$merch.'" OR s.shop_name = "'.$merch.'"';
		}
        $list = db("engineoil_replenishment")->where($where)->alias("er")->where($newwhere)->join("engineoil e" , 'e.id = er.eid')->join("yoshop_shop s",'s.shop_id = er.shop_id')->field("er.*,e.thumb,s.shop_name,e.title")->order("er.status ASC,er.id DESC")->select()->each(function($item , $key){
			$fields = array('未审核' , '未通过' , '已通过' , '已发货' , '已收货' , '完成');
            $item['status_name'] = $fields[$item['status']];
            return $item;
        })->toArray();
		$new_data = [];
		if( $list ){
			foreach( $list as $k => $v ) {
				$new_data[] = [
					'id' => $v['id'],
					'title' => $v['title'],
					'stock' => $v['stock'],
					'content' => $v['content'],
					'shop_name' => $v['shop_name'],
					'status_name' => $v['status_name'],
					'create_time' => date("Y-m-d H:i:s" , $v['create_time'])
				];
			}
		}
		$field = ['ID' , '商品信息' , '补充数量' , '说明' , '商家信息' , '状态' , '申请时间'];
		\app\common\extend\Excel::export($new_data , $field);
	}
	
	public function useyoudata() {
		$id = $this->request->param("id/d" , 0);
		if( $id <= 0 ) $this->error("信息错误");
		$data = db("engineoil_replenishment")->alias("er")->join("engineoil_shop es" , "er.eid = es.engineoil_id AND er.shop_id = es.shop_id")->field("es.id,es.engineoil_id,es.last_instock_time,er.create_time,es.stock_num")->where(['er.id' => $id])->find();
		if( !$data ) {
			$this->error("数据不存在");
		}
		$list = db("shop_yuyue_service")->alias("ys")->join("yoshop_user u","u.user_id = ys.user_id")->where( $data['last_instock_time'] . '  >= ys.`create_time` AND ys.`create_time` <= ' . $data['create_time'] . ' AND ys.`engineoil_shop_id` = ' . $data['id'] . ' AND ys.`status` IN(2,3)' )
				->field("ys.contact,ys.mobile,ys.cart_brand,ys.type,ys.yuyue_time,ys.use_capacity,ys.displacement,u.nickname")->order("id DESC")->select()->toArray();
		$data = [
			'total_you' => 0,
			'huan_you' => 0,
			'bu_you' => 0,
			'shengyu_you' => $data['stock_num']
		];
		if( $list ) {
			foreach( $list as $k => $v ){
				$data['total_you'] += $v['use_capacity'];
				if( $v['type'] == 1 ) {
					$data['huan_you'] += $v['use_capacity'];
				} else {
					$data['bu_you'] += $v['use_capacity'];
				}
			}
		}
		exit(json_encode(array('list' => $list , 'data' =>$data , 'code' => 1)));
	}
}
